package com.pangu.ui.refresh;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.RelativeLayout;

import com.pangu.AMApplication;
import com.pangu.task.mark.ATaskMark;

/**
 * 下拉刷新，上拉加载视图控制器
 * <p/>
 * Created by cuijianhui_91,panxiaodong_91
 */
public abstract class ARefreshViewController<A extends AMApplication, TaskMark extends ATaskMark, Header extends View & IPullableTracker, Content extends View & IPullable, Footer extends View & IPullableTracker>
		extends RelativeLayout {

	public static final String TAG = ARefreshViewController.class.getSimpleName();
	// 初始状态
	public static final int INIT = 0;
	// 释放刷新
	public static final int RELEASE_TO_REFRESH = 1;
	// 正在刷新
	public static final int REFRESHING = 2;
	// 释放加载
	public static final int RELEASE_TO_LOAD = 3;
	// 正在加载
	public static final int LOADING = 4;
	// 操作完毕
	public static final int DONE = 5;
	// 当前状态
	private int state = INIT;
	// 刷新回调接口
	private OnRefreshListener mListener;
	// 刷新成功
	public static final int SUCCEED = 0;
	// 刷新失败
	public static final int FAIL = 1;
	private static final long REFRESH_DEFAULT_DELAY = 1000l;
	// 按下Y坐标，上一个事件点Y坐标
	private float downY, lastY, downX, lastX;
	// 下拉的距离。注意：pullDownY和pullUpY不可能同时不为0
	public float pullDownY = 0;
	// 上拉的距离
	private float pullUpY = 0;
	// 释放刷新的距离
	private float refreshDist = 200;
	// 释放加载的距离
	private float loadMoreDist = 200;
	private RefreshTimer timer;
	// 回滚速度
	public float MOVE_SPEED = 8;
	// 第一次执行布局
	private boolean isLayout = false;
	// 在刷新过程中滑动操作
	private boolean isTouch = false;
	// 手指滑动距离与下拉头的滑动距离比，中间会随正切函数变化
	private float radio = 2;
	// 下拉头
	protected Header header;
	// 上拉头
	protected Footer footer;
	// 实现了Pullable接口的View
	protected Content content;
	// 过滤多点触碰
	private int mEvents;
	// 这两个变量用来控制pull的方向，如果不加控制，当情况满足可上拉又可下拉时没法下拉
	private boolean canPullDown = true;
	private boolean canPullUp = true;
	protected A imContext;
	protected TaskMark taskMark;
	private boolean isBeginDraging = false;
	private boolean isDispatch = false;
	private int mTouchSlop;

	public ARefreshViewController(Context context) {
		super(context);

		initView();
	}

	public ARefreshViewController(Context context, AttributeSet attrs) {
		super(context, attrs);

		initView();
	}

	public ARefreshViewController(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		initView();
	}

	private void initView() {
		this.imContext = (A) A.getInstance();
		taskMark = createTaskMark();
		// 创建内容视图
		content = createContentView();
		// 创建头部视图
		header = createRefreshHeaderView();
		// 创建底部视图
		footer = createRefreshFooterView();

		// 添加视图
		addView(header, 0, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		addView(content, 1, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		addView(footer, 2, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		timer = new RefreshTimer(new RefreshHandler(imContext.getMainLooper()));
		final ViewConfiguration configuration = ViewConfiguration.get(getContext());
		mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
	}

	private void hide() {
		timer.schedule(5);
	}

	/**
	 * 完成刷新操作，显示刷新结果。注意：刷新完成后一定要调用这个方法
	 */
	/**
	 * @param refreshResult
	 *            ARefreshViewController.SUCCEED代表成功，ARefreshViewController.
	 *            FAIL代表失败
	 */
	public void refreshFinish(int refreshResult) {
		switch (refreshResult) {
		case SUCCEED:
			// 刷新成功
			header.onRefreshSuccess();
			break;

		case FAIL:
		default:
			// 刷新失败
			header.onRefreshError();
			break;
		}

		refreshComplete(REFRESH_DEFAULT_DELAY);
	}

	/**
	 * 刷新结束状态重置
	 * 
	 * @param delay
	 */
	private void refreshComplete(long delay) {
		if (pullDownY > 0) {
			postDelayed(new Runnable() {
				@Override
				public void run() {
					changeState(DONE);
					hide();
				}
			}, delay);

		} else {
			changeState(DONE);
			hide();

		}
	}

	/**
	 * 加载完毕，显示加载结果。注意：加载完成后一定要调用这个方法
	 * 
	 * @param refreshResult
	 *            ARefreshViewController.SUCCEED代表成功，ARefreshViewController.
	 *            FAIL代表失败
	 */
	public void loadmoreFinish(int refreshResult) {
		switch (refreshResult) {
		case SUCCEED:
			// 加载成功
			footer.onRefreshSuccess();
			break;

		case FAIL:
		default:
			// 加载失败
			footer.onRefreshError();
			break;

		}

		if (pullUpY < 0) {
			changeState(DONE);
			hide();
		}
	}

	/**
	 * 切换状态
	 * 
	 * @param to
	 *            state
	 */
	private void changeState(int to) {
		state = to;
		switch (state) {
		case INIT:
			// 下拉布局初始状态
			header.onRefreshInit();
			// 上拉布局初始状态
			footer.onRefreshInit();

			break;

		case RELEASE_TO_REFRESH:
			// 释放刷新状态
			header.onReleaseToRefresh();

			break;

		case REFRESHING:
			// 正在刷新状态
			header.onRefreshing();

			break;

		case RELEASE_TO_LOAD:
			// 释放加载状态
			footer.onReleaseToRefresh();

			break;

		case LOADING:
			// 正在加载状态
			footer.onRefreshing();

			break;

		case DONE:
			// 刷新或加载完毕，啥都不做
			break;
		}
	}

	/**
	 * 不限制上拉或下拉
	 */
	private void releasePull() {
		canPullDown = true;
		canPullUp = true;
	}

	@Override
	public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
		super.requestDisallowInterceptTouchEvent(disallowIntercept);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch (ev.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			downY = ev.getY();
			downX = ev.getX();
			lastY = downY;
			lastX = downX;
			timer.cancel();
			mEvents = 0;
			releasePull();

			break;

		case MotionEvent.ACTION_POINTER_DOWN:
		case MotionEvent.ACTION_POINTER_UP:
			// 过滤多点触碰
			mEvents = -1;
			break;

		case MotionEvent.ACTION_MOVE:
			if (!isBeginDraging) {
				float xDiff = Math.abs(ev.getX() - lastX);
				float yDiff = Math.abs(ev.getY() - lastY);
				if ((xDiff > mTouchSlop || yDiff > mTouchSlop)) {
					isBeginDraging = true;
					if (xDiff > yDiff) {
						isDispatch = true;
					}
				}
				break;
			}

			if (isDispatch) {
				break;
			}

			if (mEvents == 0) {
				if (pullDownY > 0 || content.canPullDown() && canPullDown && state != LOADING) {
					// 可以下拉，正在加载时不能下拉
					// 对实际滑动距离做缩小，造成用力拉的感觉
					pullDownY = pullDownY + (ev.getY() - lastY) / radio;
					if (pullDownY < 0) {
						pullDownY = 0;
						canPullDown = false;
						canPullUp = true;
					}

					if (pullDownY > getMeasuredHeight()) {
						pullDownY = getMeasuredHeight();
					}

					// 回调下拉过程
					header.onPullToRefresh(refreshDist, pullDownY, this);

					if (state == REFRESHING) {
						// 正在刷新的时候触摸移动
						isTouch = true;
					}

				} else if (pullUpY < 0 || (content.canPullUp() && canPullUp && state != REFRESHING)) {
					// 可以上拉，正在刷新时不能上拉
					pullUpY = pullUpY + (ev.getY() - lastY) / radio;
					if (pullUpY > 0) {
						pullUpY = 0;
						canPullDown = true;
						canPullUp = false;
					}

					if (pullUpY < -getMeasuredHeight()) {
						pullUpY = -getMeasuredHeight();
					}

					// 回调上拉过程
					footer.onPullToRefresh(loadMoreDist, pullUpY, this);
					if (state == LOADING) {
						// 正在加载的时候触摸移动
						isTouch = true;
					}

				} else {
					releasePull();
				}

			} else {
				mEvents = 0;

			}

			lastY = ev.getY();
			// 根据下拉距离改变比例
			if (pullDownY > 0) {
				radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))) * 1.2f;

			} else {
				radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))) * 0.8f;
			}

			if (pullDownY > 0 || pullUpY < 0) {
				requestLayout();
			}

			if (pullDownY > 0) {
				if (pullDownY <= refreshDist && (state == RELEASE_TO_REFRESH || state == DONE)) {
					// 如果下拉距离没达到刷新的距离且当前状态是释放刷新，改变状态为下拉刷新
					changeState(INIT);
				}

				if (pullDownY >= refreshDist && state == INIT) {
					// 如果下拉距离达到刷新的距离且当前状态是初始状态刷新，改变状态为释放刷新
					changeState(RELEASE_TO_REFRESH);
				}

			} else if (pullUpY < 0) {
				// 下面是判断上拉加载的，同上，注意pullUpY是负值
				if (-pullUpY <= loadMoreDist && (state == RELEASE_TO_LOAD || state == DONE)) {
					changeState(INIT);
				}

				// 上拉操作
				if (-pullUpY >= loadMoreDist && state == INIT) {
					changeState(RELEASE_TO_LOAD);
				}
			}

			// 因为刷新和加载操作不能同时进行，所以pullDownY和pullUpY不会同时不为0，因此这里用(pullDownY +
			// Math.abs(pullUpY))就可以不对当前状态作区分了
			if ((pullDownY + Math.abs(pullUpY)) > 8) {
				// 防止下拉过程中误触发长按事件和点击事件
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}

			break;

		case MotionEvent.ACTION_UP:
			if (pullDownY > refreshDist || -pullUpY > loadMoreDist) {
				// 正在刷新时往下拉（正在加载时往上拉），释放后下拉头（上拉头）不隐藏
				isTouch = false;
			}

			// 释放刷新，开始加载数据
			if (state == RELEASE_TO_REFRESH) {
				// 状态改为正在刷新
				changeState(REFRESHING);
				// 请求新数据
				if (mListener != null) {
					mListener.onRefresh(this);
				}

			} else if (state == RELEASE_TO_LOAD) {
				// 状态改为正在加载
				changeState(LOADING);
				// 请求新数据
				if (mListener != null) {
					mListener.onLoadMore(this);

				}

			}
			hide();
			isBeginDraging = false;
			isDispatch = false;
			break;

		default:
			break;
		}

		// 事件分发交给父类
		super.dispatchTouchEvent(ev);

		return true;
	}

	/**
	 * 自动模拟手指滑动的task
	 */
	private class AutoRefreshAndLoadTask extends AsyncTask<Integer, Float, String> {
		@Override
		protected String doInBackground(Integer... params) {
			while (pullDownY < refreshDist) {
				pullDownY += MOVE_SPEED;
				publishProgress(pullDownY);

				try {
					Thread.sleep(params[0]);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			changeState(REFRESHING);
			// 刷新操作
			if (mListener != null) {
				mListener.onRefresh(ARefreshViewController.this);
			}

			hide();
		}

		@Override
		protected void onProgressUpdate(Float... values) {
			if (pullDownY > refreshDist) {
				changeState(RELEASE_TO_REFRESH);
			}
			requestLayout();
		}

	}

	/**
	 * 自动刷新
	 */
	public void autoRefresh() {
		AutoRefreshAndLoadTask task = new AutoRefreshAndLoadTask();
		task.execute(5);
	}

	/**
	 * 自动加载
	 */
	public void autoLoad() {
		pullUpY = -loadMoreDist;
		requestLayout();
		changeState(LOADING);

		// 加载操作
		if (mListener != null) {
			mListener.onLoadMore(this);
		}
	}

	/**
	 * 创建下拉头部视图
	 * 
	 * @return
	 */
	protected abstract Header createRefreshHeaderView();

	/**
	 * 创建内容视图
	 * 
	 * @return
	 */
	protected abstract Content createContentView();

	/**
	 * 创建上拉底部视图
	 * 
	 * @return
	 */
	protected abstract Footer createRefreshFooterView();

	/**
	 * 创建视图任务标记
	 * 
	 * @return
	 */
	protected abstract TaskMark createTaskMark();

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		if (!isLayout) {
			// 这里是第一次进来的时候做一些初始化
			header = (Header) getChildAt(0);
			content = (Content) getChildAt(1);
			footer = (Footer) getChildAt(2);
			isLayout = true;
			refreshDist = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
			loadMoreDist = footer.getMeasuredHeight();
		}
		// 改变子控件的布局，这里直接用(pullDownY + pullUpY)作为偏移量，这样就可以不对当前状态作区分
		header.layout(0, (int) (pullDownY + pullUpY) - header.getMeasuredHeight(), header.getMeasuredWidth(),
				(int) (pullDownY + pullUpY));
		content.layout(0, (int) (pullDownY + pullUpY), content.getMeasuredWidth(), (int) (pullDownY + pullUpY)
				+ content.getMeasuredHeight());
		footer.layout(0, (int) (pullDownY + pullUpY) + content.getMeasuredHeight(), footer.getMeasuredWidth(),
				(int) (pullDownY + pullUpY) + content.getMeasuredHeight() + footer.getMeasuredHeight());
	}

	class RefreshTimer {
		private Handler handler;
		private Timer timer;
		private RefreshTimerTask mTask;

		public RefreshTimer(Handler handler) {
			this.handler = handler;
			timer = new Timer();
		}

		public void schedule(long period) {
			if (mTask != null) {
				mTask.cancel();
				mTask = null;
			}
			mTask = new RefreshTimerTask(handler);
			timer.schedule(mTask, 0, period);
		}

		public void cancel() {
			if (mTask != null) {
				mTask.cancel();
				mTask = null;
			}
		}

		class RefreshTimerTask extends TimerTask {

			private Handler handler;

			public RefreshTimerTask(Handler handler) {
				this.handler = handler;
			}

			@Override
			public void run() {
				handler.obtainMessage().sendToTarget();
			}

		}
	}

	class RefreshHandler extends Handler {

		public RefreshHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			// 回弹速度随下拉距离moveDeltaY增大而增大
			MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
			if (!isTouch) {
				// 正在刷新，且没有往上推的话则悬停，显示"正在刷新..."
				if (state == REFRESHING && pullDownY <= refreshDist) {
					pullDownY = refreshDist;
					timer.cancel();

				} else if (state == LOADING && -pullUpY <= loadMoreDist) {
					pullUpY = -loadMoreDist;
					timer.cancel();

				}

			}
			if (pullDownY > 0) {
				pullDownY -= MOVE_SPEED;

			} else if (pullUpY < 0) {
				pullUpY += MOVE_SPEED;

			}

			if (pullDownY < 0) {
				// 已完成回弹
				pullDownY = 0;
				// 隐藏下拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
				if (state != REFRESHING && state != LOADING) {
					changeState(INIT);
				}

				timer.cancel();
				requestLayout();
			}

			if (pullUpY > 0) {
				// 已完成回弹
				pullUpY = 0;
				// 隐藏上拉头时有可能还在刷新，只有当前状态不是正在刷新时才改变状态
				if (state != REFRESHING && state != LOADING) {
					changeState(INIT);
				}

				timer.cancel();
				requestLayout();
			}

			// 刷新布局,会自动调用onLayout
			requestLayout();
			// 没有拖拉或者回弹完成
			if (pullDownY + Math.abs(pullUpY) == 0) {
				timer.cancel();
			}
		}

	}

	public void setOnRefreshListener(OnRefreshListener listener) {
		mListener = listener;
	}

	/**
	 * 刷新加载回调接口
	 */
	public interface OnRefreshListener {

		/**
		 * 刷新操作
		 */
		void onRefresh(ARefreshViewController controller);

		/**
		 * 加载操作
		 */
		void onLoadMore(ARefreshViewController controller);
	}

}
